﻿using Core;
using Core.Domain.Common;
using Core.Domain.Companys;
using Net.Web.Models.Jobs;
using Services.Companys;
using Services.Directory;
using Services.ExtendedAttributes;
using Services.Localization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Core.Domain.Customers;
using Services.Catelog;

namespace Net.Web.Controllers
{
    /// <summary>
    /// 职位控制器
    /// </summary>
    public class JobController : BaseController
    {
        #region Fields

        private readonly ICompanyService _companyService;
        private readonly IWorkContext _workContext;
        private readonly IStoreContext _storeContext;
        private readonly IJobService _jobService;
        private readonly IWebHelper _webHelper;
        private readonly ILocalizationService _localizationService;
        private readonly ICitysService _cityService;
        private readonly IExtendedAttributeService _extendService;
        private readonly ICategoryService _categoryService;
        private readonly CommonSettings _commonSetting;

        #endregion

        #region Con
        public JobController(
            IWorkContext workContext,
            IStoreContext storeContext,
            IWebHelper webHelper,
            ILocalizationService localizationService,
            ICompanyService companyService,
            ICitysService cityService,
            IJobService jobService,
            IExtendedAttributeService extendService,
            ICategoryService categoryService,
            CommonSettings commonSetting)
        {
            this._workContext = workContext;
            this._storeContext = storeContext;
            this._webHelper = webHelper;
            this._localizationService = localizationService;
            this._companyService = companyService;
            this._commonSetting = commonSetting;
            this._cityService = cityService;
            this._extendService = extendService;
            this._jobService = jobService;
            this._categoryService = categoryService;
        }
        #endregion

        #region Action
        [ValidateInput(false)]
        public ActionResult List(JobListModel model)
        {
            if (model == null)
                model = new JobListModel();

            if (model.Keyword == null)
                model.Keyword = "";

            model.Keyword = model.Keyword.Trim();

            //排序内容组建
            PrepareSortingOptions(model);

            //分页内容组建
            PreparePageSizeOptions(model,
                _commonSetting.AllowCustomersToSelectPageSize, _commonSetting.PageSizeOptions, _commonSetting.PageSize);

            //城市内容组建
            PrepareCity(model);

            PrepareExtendedAttribute(model);

            //获取属性
            var allUrl = _webHelper.GetThisPageUrl(true);
            var actionUrl = _webHelper.GetThisPageUrl(false);
            var parameter = allUrl.Replace(actionUrl + "?", "");

            List<int> values = new List<int>();
            foreach (string i in parameter.Split('&'))
            {
                if (i.Contains("extend_"))
                {
                    string value = i.Replace("extend_", "").Split('=')[1];
                    values.Add(Convert.ToInt32(value));
                }
            }

            var list = _jobService.GetJobs(name: model.Keyword, active: true, deleted: false, sort: (JobSortingEnum)model.OrderBy,
                                pageIndex: model.PageIndex, pageSize: model.PageSize);
                        

            model.Jobs = (from p in list
                              select new JobOverviewModel
                              {
                                  //City = _cityService.GetCityById(p.ci).Name,
                                  CreateOn = p.CreatedOn.ToString("MM-dd"),
                                  Id = p.Id,
                                  Memo = p.Memo,
                                  Name = p.Name,
                              }).ToList();

            return View(model);
        }

        public ActionResult CreateJob()
        {

            var customer = _workContext.CurrentCustomer;

            JobCreateModel model = new JobCreateModel();

            foreach (WorkType enumValue in Enum.GetValues(typeof(WorkType)))
            {
                model.AvailableWorkType.Add(new SelectListItem()
                {
                    Text = enumValue.GetLocalizedEnum(_localizationService, _workContext),
                    Value = enumValue.ToString(),
                    Selected = false,
                });
            }
            var cateList = _categoryService.GetAllCategoriesByParentCategoryId(0);
            model.AvailableCategory = (from p in cateList
                                       select new SelectListItem
                                       {
                                           Text = p.Name,
                                           Value = p.Id.ToString(),
                                       }).ToList();
            //if (!customer.IsRegistered())
            //{
            //    return RedirectToRoute("Register");
            //}

            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult GetCategoryById(string parentId)
        {

            if (String.IsNullOrEmpty(parentId))
                throw new ArgumentNullException("parentId");

            var categoryList = _categoryService.GetAllCategoriesByParentCategoryId(Convert.ToInt32(parentId));
            var model = (from p in categoryList
                         select new SelectListItem
                         {
                             Value = p.Id.ToString(),
                             Text = p.Name,
                         }).ToList();

            return Json(model, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Utilities

        [NonAction]
        protected virtual void PrepareSortingOptions(JobListModel pagingFilteringModel)
        {
            if (pagingFilteringModel == null)
                throw new ArgumentNullException("pagingFilteringModel");

            foreach (JobSortingEnum enumValue in Enum.GetValues(typeof(JobSortingEnum)))
            {
                var currentPageUrl = _webHelper.GetThisPageUrl(true);
                var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + ((int)enumValue).ToString(), null);

                pagingFilteringModel.AvailableSortOptions.Add(new SelectListItem()
                {
                    Text = enumValue.GetLocalizedEnum(_localizationService, _workContext),
                    Value = sortUrl,
                    Selected = enumValue == (JobSortingEnum)pagingFilteringModel.OrderBy
                });
            }
        }

        [NonAction]
        protected virtual void PrepareCity(JobListModel pagingFilteringModel)
        {
            if (pagingFilteringModel == null)
                throw new ArgumentNullException("PrepareCity");

            var cities = _cityService.GetCities(hot: true, pageIndex: 0, pageSize: 7);

            var currentPageUrl = _webHelper.GetThisPageUrl(true);
            pagingFilteringModel.AvailableCity = (from p in cities
                                                  select new SelectListItem()
                                                  {
                                                      Text = p.Name,
                                                      Value = _webHelper.ModifyQueryString(currentPageUrl, "city=" + p.Id.ToString(), null),
                                                      Selected = p.Id == pagingFilteringModel.City,
                                                  }).ToList();
        }

        [NonAction]
        protected virtual void PreparePageSizeOptions(JobListModel pagingFilteringModel,
            bool allowCustomersToSelectPageSize, string pageSizeOptions, int fixedPageSize)
        {
            if (pagingFilteringModel == null)
                throw new ArgumentNullException("pagingFilteringModel");


            if (pagingFilteringModel.PageNumber <= 0)
            {
                pagingFilteringModel.PageNumber = 1;
            }
            if (allowCustomersToSelectPageSize && pageSizeOptions != null)
            {
                var pageSizes = pageSizeOptions.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (pageSizes.Any())
                {
                    if (pagingFilteringModel.PageSize <= 0 || !pageSizes.Contains(pagingFilteringModel.PageSize.ToString()))
                    {
                        int temp = 0;

                        if (int.TryParse(pageSizes.FirstOrDefault(), out temp))
                        {
                            if (temp > 0)
                            {
                                pagingFilteringModel.PageSize = temp;
                            }
                        }
                    }

                    var currentPageUrl = _webHelper.GetThisPageUrl(true);
                    var sortUrl = _webHelper.ModifyQueryString(currentPageUrl, "pagesize={0}", null);
                    sortUrl = _webHelper.RemoveQueryString(sortUrl, "pagenumber");

                    foreach (var pageSize in pageSizes)
                    {
                        int temp = 0;
                        if (!int.TryParse(pageSize, out temp))
                        {
                            continue;
                        }
                        if (temp <= 0)
                        {
                            continue;
                        }

                        pagingFilteringModel.PageSizeOptions.Add(new SelectListItem()
                        {
                            Text = pageSize,
                            Value = String.Format(sortUrl, pageSize),
                            Selected = pageSize.Equals(pagingFilteringModel.PageSize.ToString(), StringComparison.InvariantCultureIgnoreCase)
                        });
                    }

                    if (pagingFilteringModel.PageSizeOptions.Any())
                    {
                        pagingFilteringModel.PageSizeOptions = pagingFilteringModel.PageSizeOptions.OrderBy(x => int.Parse(x.Text)).ToList();

                        if (pagingFilteringModel.PageSize <= 0)
                        {
                            pagingFilteringModel.PageSize = int.Parse(pagingFilteringModel.PageSizeOptions.FirstOrDefault().Text);
                        }
                    }
                }
            }
            else
            {
                pagingFilteringModel.PageSize = fixedPageSize;
            }

            if (pagingFilteringModel.PageSize <= 0)
            {
                pagingFilteringModel.PageSize = fixedPageSize;
            }
        }

        /// <summary>
        /// 组建属性
        /// </summary>
        /// <param name="pagingFilteringModel"></param>
        /// <param name="command"></param>
        protected virtual void PrepareExtendedAttribute(JobListModel pagingFilteringModel)
        {
            if (pagingFilteringModel == null)
                throw new ArgumentNullException("PrepareExtendedAttribute");

            var extends = _extendService.GetExtendedAttributeByEnum(Core.Domain.ExtendEnum.Jobs);

            var currentPageUrl = _webHelper.GetThisPageUrl(true);

            pagingFilteringModel.AvailableExtend = (from p in extends
                                                    select new JobExtendModel()
                                                    {
                                                        Id = p.Id,
                                                        Name = p.Name,
                                                        ExtendValues = (from s in _extendService.GetAllExtendValues(p.Id)
                                                                        select new SelectListItem()
                                                                        {
                                                                            Text = s.Value,
                                                                            Value = _webHelper.ModifyQueryString(currentPageUrl, "extend_" + p.Id.ToString() + "=" + s.Id.ToString(), null),
                                                                            Selected = currentPageUrl.Contains("extend_" + p.Id.ToString() + "=" + s.Id.ToString())
                                                                        }).ToList(),
                                                    }).ToList();
        }
        #endregion
    }
}